package com.bonc.apicreator.ctrl;


import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.bonc.apicreator.codebuild.action.CodeBuildAction;
import com.bonc.apicreator.dao.ProjectDao;
import com.bonc.apicreator.entity.Project;


/**
 * 文件的controller
 *
 * @author liuchang
 * @version 2016年8月8日
 * @see fileController
 * @since
 */
@Controller
public class FileController {
    /**
     * 日志对象
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(FileController.class);

    /**
     * Dao
     */
    @Autowired
    private ProjectDao projectDao;

    /**
     * code
     */
    @Autowired
    private CodeBuildAction codeBuildAction;

    /**
     * Description: 下载
     * 
     * @param id
     * @param request
     * @param response
     *            void
     * @see
     */

    @RequestMapping(value = {"/download"})
    public void download(Long id, HttpServletRequest request, HttpServletResponse response) {

        Project project = projectDao.findOne(id);
        String fullPath = codeBuildAction.getZip(project);

        try {

            response.setContentType(request.getServletContext().getMimeType(fullPath));
            response.setHeader("Content-Disposition",
                "attachment;filename=" + project.getCode() + ".zip");
            InputStream inStream = new FileInputStream(fullPath);

            ServletOutputStream outputStream = response.getOutputStream();
            byte[] b = new byte[100];
            int len;
            while ((len = inStream.read(b)) > 0) {
                outputStream.write(b, 0, len);
            }
            inStream.close();
            outputStream.close();
        }
        catch (IOException e) {
            LOGGER.error("Download Failed", e);
        }
    }
}
